
#import "TorrentMagicViewController.h"

@implementation TorrentMagicViewController

//
// torrent info
//
@synthesize torrentInfo														= _torrentInfo;

//
// user type
//
@synthesize userType														= _userType;

//
// duration
//
@synthesize duration														= _duration;

//
// magic type
//
@synthesize magicType														= _magicType;

//
// need count
//
@synthesize needCount														= _needCount;

//
// karma count
//
@synthesize karmaCount														= _karmaCount;

//
// uCoin
//
@synthesize uCoin															= _uCoin;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// setup title
	//
	self.title																= NSLocalizedStringFromTable(@"Torrent Magic", @"TorrentMagicViewController", nil);
	self.needCount															= @"?";
	self.karmaCount															= @"?";
	self.uCoin																= @"?";
	self.userType															= 0;
	self.magicType															= 2;
	self.duration															= 24;
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.torrentInfo														= nil;
	self.needCount															= nil;
	self.karmaCount															= nil;
	self.uCoin																= nil;
	
	[super dealloc];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return 3;
}

//
// get title
//
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	if(section)
		return nil;
	
	NSString* magicType														= nil;
	if(self.torrentInfo.downRate.length && self.torrentInfo.upRate.length)
		magicType															= [NSString stringWithFormat:@"%@ / %@", self.torrentInfo.upRate, self.torrentInfo.downRate];
	else if(!self.torrentInfo.downRate.length && self.torrentInfo.upRate.length)
		magicType															= NSLocalizedStringFromTable(self.torrentInfo.upRate, @"TorrentMagicViewController", nil);
	else
		magicType															= NSLocalizedStringFromTable(@"None", @"TorrentMagicViewController", nil);;
	
	return [NSString stringWithFormat:@"%@ @ %@", self.torrentInfo.title, magicType];
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return section == 0 ? 3 : (section == 1 ? 3 : 3);
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	UITableViewCell* theCell												= nil;
	if(indexPath.section  == 0)
	{
		UITextField* textField												= [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 80, 21)] autorelease];
		theCell																= [tableView dequeueReusableCellWithIdentifier:@"v1"];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"v1"] autorelease];
		
		switch(indexPath.row)
		{
			//
			// user type
			//
		case 0:
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Range", @"TorrentMagicViewController", nil);
			textField.placeholder											= NSLocalizedStringFromTable(@"range", @"TorrentMagicViewController", nil);
			textField.text													= self.userType == 0 ? NSLocalizedStringFromTable(@"Global", @"TorrentMagicViewController", nil) : NSLocalizedStringFromTable(@"Self only", @"TorrentMagicViewController", nil);
			break;
			
			//
			// magic type
			//
		case 1:
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Magic Effect", @"TorrentMagicViewController", nil);
			textField.placeholder											= NSLocalizedStringFromTable(@"effect type", @"TorrentMagicViewController", nil);
			textField.text													= [self textForMagicType:self.magicType];
			break;
			
			//
			// duration
			//
		case 2:
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Duration (hours)", @"TorrentMagicViewController", nil);
			textField.placeholder											= NSLocalizedStringFromTable(@"duration in hours", @"TorrentMagicViewController", nil);
			textField.text													= [NSString stringWithFormat:@"%d", self.duration];
			break;
		}
		
		textField.tag														= indexPath.row;
		textField.adjustsFontSizeToFitWidth									= YES;
		textField.autocorrectionType										= UITextAutocorrectionTypeNo;
		textField.autocapitalizationType									= UITextAutocapitalizationTypeNone;
		textField.clearButtonMode											= UITextFieldViewModeNever;
		textField.delegate													= self;
		theCell.accessoryView												= textField;
		theCell.selectionStyle												= UITableViewCellSelectionStyleNone;
		theCell.accessoryType												= UITableViewCellAccessoryNone;
	}
	else if(indexPath.section == 1)
	{
		theCell																= [tableView dequeueReusableCellWithIdentifier:@"v1"];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"v1"] autorelease];
		
		if(indexPath.row == 0)
		{
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Need Karma", @"TorrentMagicViewController", nil);
			theCell.detailTextLabel.text									= self.needCount;
			theCell.detailTextLabel.textColor								= [self.needCount isEqualToString:@"?"] || self.needCount.doubleValue < self.karmaCount.doubleValue ? [UIColor grayColor] : [UIColor redColor];
		}
		else if(indexPath.row == 1)
		{
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Current Karma", @"TorrentMagicViewController", nil);
			theCell.detailTextLabel.text									= self.karmaCount;
		}
		else if(indexPath.row == 2)
		{
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Current uCoin", @"TorrentMagicViewController", nil);
			theCell.detailTextLabel.text									= self.uCoin;
		}

		theCell.accessoryType												= UITableViewCellAccessoryNone;
		theCell.selectionStyle												= UITableViewCellSelectionStyleNone;
	}
	else if(indexPath.section == 2)
	{
		theCell																= [tableView dequeueReusableCellWithIdentifier:@"d"];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"d"] autorelease];
		
		
		if(indexPath.row == 0)
		{
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Compute Needed Count", @"TorrentMagicViewController", nil);
		}
		else if(indexPath.row == 1)
		{
			NSString* exchangeCount											= [self computeExchangeCount];
			theCell.textLabel.text											= [NSString stringWithFormat:NSLocalizedStringFromTable(@"Need Exchange uCoin: %@", @"TorrentMagicViewController", nil), exchangeCount];
		}
		else
		{
			theCell.textLabel.text											= NSLocalizedStringFromTable(@"Just Do it", @"TorrentMagicViewController", nil);
		}
		
		theCell.accessoryType												= UITableViewCellAccessoryNone;
		theCell.textLabel.textAlignment										= UITextAlignmentCenter;
	}
	
	return theCell;
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	if(indexPath.section == 2)
	{
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		if(indexPath.row == 0)
		{
			NexusClient* client												= [NexusClient sharedClient];
			id getUserDetailsFinished = [[^void(GetUserDetailsRequest* httpRequest)
			{
			   [ActivityView removeView];
			   if(!httpRequest.error && httpRequest.response.statusCode == 200)
			   {
				   self.karmaCount											= [httpRequest.userDetails.karma stringByReplacingOccurrencesOfString:@"," withString:@""];
				   self.uCoin												= [httpRequest.userDetails.uCoin stringByReplacingOccurrencesOfString:@"," withString:@""];
				   [self.tableView reloadData];
			   }
			   else
			   {
				   NSString* message										= [httpRequest errorDescription];
				   NSString* title											= NSLocalizedStringFromTable(@"Get Current Karma/uCoin Count Failed", @"TorrentMagicViewController", nil);
				   [UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
			   }		
			} copy] autorelease];
			
			id getRequiredCountFinished = ^void(TorrentMagicRequest* httpRequest)
			{
				if(!httpRequest.error && httpRequest.response.statusCode == 200)
				{
					self.needCount											= [httpRequest.needCount stringByReplacingOccurrencesOfString:@"," withString:@""];
					[[ActivityView currentView] updateText:NSLocalizedStringFromTable(@"Getting Current Karma/uCoin Count", @"TorrentMagicViewController", nil)];
					[client getUserDetails:[DataCenter sharedDataCenter].userId callback:getUserDetailsFinished];
				}
				else
				{
					[ActivityView removeView];
					NSString* message										= [httpRequest errorDescription];
					NSString* title											= NSLocalizedStringFromTable(@"Compute Needed Karma Count Failed", @"TorrentMagicViewController", nil);
					[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
				}
			};
			[ActivityView showActivityView:NSLocalizedStringFromTable(@"Computing Needed Karma Count", @"TorrentMagicViewController", nil) networking:YES];
			[client getRequiredKarmaForTorrent:self.torrentInfo.torrentId magicType:self.magicType userType:self.userType duration:self.duration callback:getRequiredCountFinished];
		}
		else if(indexPath.row == 1)
		{
			NexusClient* client												= [NexusClient sharedClient];
			NSInteger needCount												= [self computeExchangeCount].integerValue;
			if(needCount)
			{
				id getUserDetailsFinished = [[^void(GetUserDetailsRequest* httpRequest)
				{
				  [ActivityView removeView];
				  if(!httpRequest.error && httpRequest.response.statusCode == 200)
				  {
					  self.karmaCount											= [httpRequest.userDetails.karma stringByReplacingOccurrencesOfString:@"," withString:@""];
					  self.uCoin												= [httpRequest.userDetails.uCoin stringByReplacingOccurrencesOfString:@"," withString:@""];
					  [self.tableView reloadData];
				  }
				  else
				  {
					  NSString* message										= [httpRequest errorDescription];
					  NSString* title											= NSLocalizedStringFromTable(@"Get Current Karma/uCoin Count Failed", @"TorrentMagicViewController", nil);
					  [UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
				  }		
				} copy] autorelease];
				
				id exchangeFinished = ^void(NexusHttpRequest* httpRequest)
				{
					if(!httpRequest.error && httpRequest.response.statusCode == 200)
					{
						[[ActivityView currentView] updateText:NSLocalizedStringFromTable(@"Getting Current Karma/uCoin Count", @"TorrentMagicViewController", nil)];
						[client getUserDetails:[DataCenter sharedDataCenter].userId callback:getUserDetailsFinished];
					}
					else
					{
						[ActivityView removeView];
						NSString* message										= [httpRequest errorDescription];
						NSString* title											= NSLocalizedStringFromTable(@"Exchange uCoin To Karma Failed", @"TorrentMagicViewController", nil);
						[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
					}
				};
				[ActivityView showActivityView:NSLocalizedStringFromTable(@"Exchanging uCoin To Karma", @"TorrentMagicViewController", nil) networking:YES];
				[client exchangeUCoinToKarma:needCount callback:exchangeFinished];
			}
		}
		else
		{
			NexusClient* client												= [NexusClient sharedClient];
			id getTorrentDetailsFinished = [[^void(GetTorrentDetailsRequest* httpRequest)
			{
				[ActivityView removeView];
				if(!httpRequest.error && httpRequest.response.statusCode == 200)
				{
					self.torrentInfo.size									= httpRequest.torrentInfo.size;
					self.torrentInfo.uploadDate								= httpRequest.torrentInfo.uploadDate;
					self.torrentInfo.seederCount							= httpRequest.torrentInfo.seederCount;
					self.torrentInfo.leecherCount							= httpRequest.torrentInfo.leecherCount;
					self.torrentInfo.upRate									= httpRequest.torrentInfo.upRate;
					self.torrentInfo.downRate								= httpRequest.torrentInfo.downRate;
					self.torrentInfo.magicExpire							= httpRequest.torrentInfo.magicExpire;
					self.torrentInfo.torrentDescription						= httpRequest.torrentInfo.torrentDescription;
					self.torrentInfo.aniDB									= httpRequest.torrentInfo.aniDB;
					self.torrentInfo.unread									= YES;
					[[DataCenter sharedDataCenter] checkAddTorrent:self.torrentInfo];
					[self.tableView reloadData];
					[UIAlertView alertViewWithTitle:NSLocalizedStringFromTable(@"Finished", @"TorrentMagicViewController", nil) message:NSLocalizedStringFromTable(@"Do Torrent Magic Finished", @"TorrentMagicViewController", nil) cancel:NSLocalizedString(@"OK", nil)];
				}
				else
				{
					[UIAlertView alertViewWithTitle:NSLocalizedStringFromTable(@"Get Torrent Details Failed", @"TorrentDetailsViewController", nil) message:[httpRequest errorDescription] cancel:NSLocalizedString(@"OK", nil)];
				}
			} copy] autorelease];
			
			id doMagicFinished = ^void(TorrentMagicRequest* httpRequest)
			{
				if(!httpRequest.error && httpRequest.response.statusCode == 200)
				{
					NSString* resultScript									= [[[NSString alloc] initWithData:httpRequest.dataBuffer encoding:NSUTF8StringEncoding] autorelease];
					if([resultScript hasPrefix:@"<script type=\"text/javascript\">window.location.href = '?action=detail&id="])
					{
						[[ActivityView currentView] updateText:NSLocalizedStringFromTable(@"Getting Torrent Details", @"TorrentMagicViewController", nil)];
						[client getTorrentDetails:self.torrentInfo.torrentId callback:getTorrentDetailsFinished];
					}
					else
					{
						[ActivityView removeView];
						[UIAlertView alertViewWithTitle:NSLocalizedStringFromTable(@"Do Torrent Magic Failed", @"TorrentMagicViewController", nil) message:NSLocalizedStringFromTable(@"Not Enough Karma?", @"TorrentMagicViewController", nil) cancel:NSLocalizedString(@"OK", nil)];
					}
				}
				else
				{
					[ActivityView removeView];
					[UIAlertView alertViewWithTitle:NSLocalizedStringFromTable(@"Do Torrent Magic Failed", @"TorrentMagicViewController", nil) message:[httpRequest errorDescription] cancel:NSLocalizedString(@"OK", nil)];
				}
			};
			[ActivityView showActivityView:NSLocalizedStringFromTable(@"Doing Torrent Magic", @"TorrentMagicViewController", nil) networking:YES];
			[client doMagic:self.magicType forTorrent:self.torrentInfo.torrentId userType:self.userType duration:self.duration callback:doMagicFinished];
		}
	}
}

//
// cancel edit
//
- (void)cancelEdit:(id)sender
{
	[self.tableView endEditing:YES];
}

//
// commit edit
//
- (void)commitEdit:(id)sender
{
	[self.tableView endEditing:YES];
}

//
// show picker view
//
- (void)showPicker:(id)sender
{
	UITextField* textField													= (UITextField*)sender;
	UIPickerView* pickerView												= [[[UIPickerView alloc] init] autorelease];
	[pickerView sizeToFit];
	pickerView.autoresizingMask												= UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	pickerView.delegate														= self;
	pickerView.dataSource													= self;
	pickerView.showsSelectionIndicator										= YES;
	pickerView.tag															= textField.tag;
	textField.inputView														= pickerView;
	
	UIToolbar* doneButtonView												= [[[UIToolbar alloc] init] autorelease];
	doneButtonView.barStyle													= UIBarStyleBlack;
	doneButtonView.translucent												= YES;
	doneButtonView.tintColor												= nil;
	[doneButtonView sizeToFit];
	
	UIBarButtonItem* flexSpace												= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
	UIBarButtonItem* doneButton												= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectPickerItem:)] autorelease];
	doneButton.tag															= textField.tag;
	[doneButtonView setItems:[NSArray arrayWithObjects:flexSpace, doneButton, nil]];
	textField.inputAccessoryView											= doneButtonView;
	
	[pickerView reloadAllComponents];
	if(pickerView.tag == 0)
		[pickerView selectRow:self.userType inComponent:0 animated:NO];
	else if(pickerView.tag == 1)
		[pickerView selectRow:self.magicType inComponent:0 animated:NO];
	else
		[pickerView selectRow:self.duration - 24 inComponent:0 animated:NO];
}

//
// select picker item
//
- (void)selectPickerItem:(id)sender
{
	UIBarButtonItem* doneButton												= (UIBarButtonItem*)sender;
	UITableViewCell* theCell												= [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:doneButton.tag inSection:0]];
	UITextField* textField													= (UITextField*)theCell.accessoryView;
	[self textFieldShouldReturn:textField];
}

//
// components
//
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
	return 1;
}

//
// items
//
- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return pickerView.tag == 0 ? 2 : (pickerView.tag == 1 ? 6 : 120 - 24 + 1);
}

//
// title
//
- (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	if(pickerView.tag == 0)
		return row == 0 ? NSLocalizedStringFromTable(@"Global", @"TorrentMagicViewController", nil) : NSLocalizedStringFromTable(@"Self only", @"TorrentMagicViewController", nil);
	
	if(pickerView.tag == 1)
		return [self textForMagicType:row];
	
	return [NSString stringWithFormat:@"%d", row + 24];
}

//
// select row
//
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	UITableViewCell* theCell												= [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:pickerView.tag inSection:0]];
	UITextField* textField													= (UITextField*)theCell.accessoryView;
	textField.text															= [self pickerView:pickerView titleForRow:row forComponent:component];
}

//
// disable text change
//
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
	return NO;
}

//
// begin editing
//
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
	[self showPicker:textField];
}

//
// end editing
//
- (void)textFieldDidEndEditing:(UITextField*)textField
{
	switch(textField.tag)
	{
	case 0:
		self.userType														= [textField.text isEqualToString:NSLocalizedStringFromTable(@"Global", @"TorrentMagicViewController", nil)] ? 0 : 1;
		break;
			
	case 1:
		self.magicType														= [self magicTypeForText:textField.text];
		break;
			
	case 2:
		self.duration														= textField.text.integerValue;
		break;
	}
}

//
// return
//
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
	switch(textField.tag)
	{
	case 0:
	case 1:
		[[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:textField.tag + 1 inSection:0]].accessoryView becomeFirstResponder];
		break;
		
	case 2:
		[self commitEdit:textField];
		break;
	}
	return YES;
}

//
// text for magic type
//
- (NSString*)textForMagicType:(NSInteger)magicType
{
	if(magicType == 0)
		return NSLocalizedStringFromTable(@"Free", @"TorrentMagicViewController", nil);
	
	if(magicType == 1)
		return NSLocalizedStringFromTable(@"2x", @"TorrentMagicViewController", nil);
	
	if(magicType == 2)
		return NSLocalizedStringFromTable(@"2xFree", @"TorrentMagicViewController", nil);
	
	if(magicType == 3)
		return NSLocalizedStringFromTable(@"50%", @"TorrentMagicViewController", nil);
	
	if(magicType == 4)
		return NSLocalizedStringFromTable(@"2x50%", @"TorrentMagicViewController", nil);
	
	if(magicType == 5)
		return NSLocalizedStringFromTable(@"30%", @"TorrentMagicViewController", nil);
	
	return NSLocalizedStringFromTable(@"Custom", @"TorrentMagicViewController", nil);
}

//
// magic type for text
//
- (NSInteger)magicTypeForText:(NSString*)magicType
{
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"Free", @"TorrentMagicViewController", nil)])
		return 0;
	
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"2x", @"TorrentMagicViewController", nil)])
		return 1;
	
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"2xFree", @"TorrentMagicViewController", nil)])
		return 2;
	
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"50%", @"TorrentMagicViewController", nil)])
		return 3;
	
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"2x50%", @"TorrentMagicViewController", nil)])
		return 4;
	
	if([magicType isEqualToString:NSLocalizedStringFromTable(@"30%", @"TorrentMagicViewController", nil)])
		return 5;
	
	return 6;
}

//
// compute exchange count
//
- (NSString*)computeExchangeCount
{
	if([self.needCount isEqualToString:@"?"])
		return @"?";
	
	double needCount														= self.needCount.doubleValue;
	double karmaCount														= self.karmaCount.doubleValue;
	double uCoinCount														= self.uCoin.doubleValue;
	double exchangeCount													= (needCount - karmaCount + 20) * 2;
	
	if(exchangeCount < 0)
		return @"0";
	
	if(uCoinCount  < exchangeCount)
		return NSLocalizedStringFromTable(@"Not Enough", @"TorrentMagicViewController", nil);
	
	return [NSString stringWithFormat:@"%d", (NSInteger)exchangeCount];
}

@end
